#include "Video_Convert.h"



Video_Convert::Video_Convert()
    :width_(0)
    ,height_(0)
    ,fmt_(AV_PIX_FMT_NONE)
{

}

Video_Convert::~Video_Convert()
{
    Close();
}

bool Video_Convert::Open(int32_t in_width, int32_t in_height, AVPixelFormat in_fmt, int32_t out_width, int32_t out_height, AVPixelFormat out_fmt)
{
    //初始化这个视频转化格式上下文
    if(swsContext_)
    {
        return false;
    }

    //chushihua
    swsContext_ = sws_getContext(in_width,in_height,in_fmt,
                                out_width,out_height,out_fmt,
                                 SWS_BICUBIC,NULL,NULL,NULL);
    width_ = out_width;
    height_ = out_height;
    fmt_ = out_fmt;
    return swsContext_!=nullptr;
}

void Video_Convert::Close()
{
    if(swsContext_)
    {
        sws_freeContext(swsContext_);
        swsContext_ = nullptr;
    }
}

int32_t Video_Convert::Convret(AVFramePtr in_frame, AVFramePtr &out_frame)
{
    //开始视频格式转换
    if(!swsContext_)
    {
        return -1;
    }

    //创建输出帧
    out_frame = AVFramePtr(av_frame_alloc(),[](AVFrame* p){av_frame_free(&p);});

    out_frame->width = width_;
    out_frame->height = height_;
    out_frame->format = fmt_;
    //pts
    out_frame->pts = in_frame->pts;
    //dts
    out_frame->pkt_dts = in_frame->pkt_dts;

    if(av_frame_get_buffer(out_frame.get(),0)!=0)
    {
        return -1;
    }
    //kaishizhuanhuangeshi
    int32_t heigt_slice = sws_scale(swsContext_,in_frame->data,in_frame->linesize,0,
                                    in_frame->height,out_frame->data,out_frame->linesize);
    if(heigt_slice < 0)
    {
        return -1;
    }
    return heigt_slice;

}
